from flask import Flask, render_template, request
from flask_mysqldb import MySQL

# app = Flask(__name__)
# # mysql = MySQL()
#
#
# app.config['MYSQL_USER'] = 'j2ee'
# app.config['MYSQL_PASSWORD'] = 'j2ee'
# app.config['MYSQL_DB'] = 'ieven_practice'
# app.config['MYSQL_HOST'] = 'localhost'
# app.config['MYSQL_PORT'] = 3306
# mysql = MySQL(app)


def create_app(config=None):
    app1 = Flask(__name__)
    app1.config.update(dict(
        MYSQL_USER='j2ee',
        MYSQL_PASSWORD='j2ee',
        MYSQL_DB='ieven_practice',
        MYSQL_HOST='localhost',
        MYSQL_PORT=3306
    ))
    app1.config.update(config or {})
    app1.config.from_envvar('FLASKR_SETTINGS', silent=True)
    return app1


app = create_app()
mysql = MySQL(app)


@app.route("/")
def index():
    # print("hello")
    return render_template('layout.html')


@app.route("/select_all2/")
def select_all2():
    db = mysql.connection
    cur = db.cursor()
    try:
        cur.execute('''SELECT mac, imei FROM mac_im''')
        rv = cur.fetchall()
        return render_template('layout.html', entries=rv)
    finally:
        cur.close()


@app.route("/select_mac2")
def select_mac2():
    mac = request.args.get('mac')
    db = mysql.connection
    cur = db.cursor()
    try:
        sql_str = "SELECT mac, imei FROM mac_im WHERE mac LIKE '%{}%'".format(mac)
        cur.execute(sql_str)
        rv = cur.fetchall()
        # return str(rv)
        return render_template('layout.html', entries=rv, mac=mac)
    finally:
        cur.close()


@app.route("/select_imei2")
def select_imei2():
    imei = request.args.get('imei')
    db = mysql.connection
    cur = db.cursor()
    try:
        sql_str = "SELECT mac, imei FROM mac_im WHERE imei LIKE '%{}%'".format(imei)
        cur.execute(sql_str)
        rv = cur.fetchall()
        # return str(rv)
        return render_template('layout.html', entries=rv, imei=imei)
    finally:
        cur.close()


@app.route("/select_all/")
def select_all():
    db = mysql.connection
    cur = db.cursor()
    try:
        cur.execute('''SELECT mac, imei FROM mac_im''')
        rv = cur.fetchall()
        return str(rv)
    finally:
        cur.close()


@app.route("/select_mac/<mac>")
def select_mac(mac):
    db = mysql.connection
    cur = db.cursor()
    try:
        sql_str = "SELECT mac, imei FROM mac_im WHERE mac LIKE '%{}%'".format(mac)
        cur.execute(sql_str)
        rv = cur.fetchall()
        return str(rv)
        # return render_template('show_entries.html', entries=rv)
    finally:
        cur.close()
        # db.close()


@app.route("/select_imei/<imei>")
def select_imei(imei):
    db = mysql.connection
    cur = db.cursor()
    try:
        sql_str = "SELECT mac, imei FROM mac_im WHERE imei LIKE '%{}%'".format(imei)
        cur.execute(sql_str)
        rv = cur.fetchall()
        return str(rv)
    finally:
        cur.close()
        # db.close()


if __name__ == "__main__":
    app.run()
